package com.dongdong.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdong.utils.JwtUtil;
import com.dongdong.utils.Result;
import com.dongdong.utils.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;


@Component
@Order(-1)
public class UserLoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${exclude.url}'.empty?'null':'${exclude.url}'.split(',')}")
    private Set<String> urls;

    AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        判断是否为拦截或放行请求
        String path = exchange.getRequest().getURI().getPath();
        Boolean flag = false;
        for (String url : urls) {
            if (matcher.match(url, path)) {
               flag = true;
               break;
            }
        }
        if (flag){
            //        获取token并判断
            HttpHeaders headers = exchange.getRequest().getHeaders();
            String token = headers.getFirst("accessToken");
            if (token == null || token.isEmpty()) {
                return getMono(exchange);
            }
//        判断token是否有效
            try {
//            ExpiredJwtException token超时异常
//            MalformedJwtException  token被修改异常
                jwtUtil.parseJwt(token);
            } catch (Exception e) {
                return getMono(exchange);
            }
        }

        return chain.filter(exchange);
    }

    private static Mono<Void> getMono(ServerWebExchange exchange) {
//        Result<Object> result = new Result<>(ResultParam.TOKEN_INVALID_CODE, ResultParam.TOKEN_INVALID_MSG);

        Result result = Result.DATA(ResultEnum.TOKEN_INVALID);
        ServerHttpResponse response = exchange.getResponse();
//        设置响应码
        response.setStatusCode(HttpStatus.OK);
//        设置响应头  （解决中文乱码）
        response.getHeaders().add("content-Type","application/json;charset=utf-8");
//        判断返回的是否为空值SerializerFeature.WriteMapNullValue
        byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        Mono<DataBuffer> mono = Mono.just(wrap);
        return response.writeWith(mono);
    }
}
